package com.heima.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.heima.config.AliOssConfigProperties;
import com.heima.service.OSSAliyunFileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.InputStream;
@Slf4j
@Service
public class OSSAliyunFileStorageServiceImpl implements OSSAliyunFileStorageService {

    @Autowired
    private OSS ossClient;

    @Autowired
    private AliOssConfigProperties aliOssConfigProperties;

    /**
     * 文件上传
     * @param fileName
     * @param inputStream
     * @return
     */
    @Override
    public String store(String fileName, InputStream inputStream) {
        String url = null;
        if(ObjectUtils.isEmpty(inputStream)){
            log.error("上传文件：fileName{}文件流为空",fileName);
            return url;
        }
        log.info("OSS文件上传开始：{}",fileName);

        try {
            String bucketName = aliOssConfigProperties.getBucketName();
            PutObjectRequest request = new PutObjectRequest(bucketName, fileName, inputStream);
            PutObjectResult result = ossClient.putObject(request);
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if(ObjectUtil.isNotEmpty(request)){
                log.info("OSS文件上传成功：{}",fileName);
            }
        } catch (OSSException e) {
            log.info("OSS文件上传错误：{}",e);
        } catch (ClientException e) {
            log.info("OSS文件上传客户端错误：{}",e);
        }
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder.append(aliOssConfigProperties.getBucketName())
                .append(".")
                .append(aliOssConfigProperties.getEndpoint())
                .append("/")
                .append(fileName);
        return stringBuilder.toString();
    }
}
